package com.lu.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lu.reggie.common.R;
import com.lu.reggie.dto.DishDto;
import com.lu.reggie.entity.*;
import com.lu.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author 况山云
 * @since 2022-08-22
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private ICategoryService iCategoryService;
    @Autowired
    private IDishService iDishService;
    @Autowired
    private IDishFlavorService iDishFlavorService;
    @Autowired
    private ISetmealDishService iSetmealDishService;
    @Autowired
    private ISetmealService iSetmealService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 菜品添加
     * 必须要保证数据库和redis缓存中的数据的一致性
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        iDishService.saveWithFlavor(dishDto);
       /* //1.全部清除,先获取所有菜品的数据的key
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        //2.精准清除当前分类下的菜品数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("菜品添加成功!");
    }

    /**
     * 菜品分页条件查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //分页构造器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //过滤
        queryWrapper.like(name != null, Dish::getName, name);
        //排序
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //分页查询
        iDishService.page(dishPage, queryWrapper);
        //拷贝，records第一次查询为空，需要重新查询
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<Dish> records = dishPage.getRecords();
        //将每一个菜品信息拿出，取出id查询菜品口味对象，再取出名称封装到dto对象中
        List<DishDto> dishDtos = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //id查询
            Category category = iCategoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtos);
        return R.success(dishDtoPage);
    }

    /**
     * 菜品修改回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getByIdWithFlavor(@PathVariable Long id) {
        DishDto dishDto = iDishService.findByIdWithFlavor(id);
        return R.success(dishDto);
    }


    /**
     * 菜品修改
     * 直接全部清除redis的缓存，因为修改还能修改菜品的分类
     * 影响多个表的数据
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("修改的菜品为:{}", dishDto.toString());
        iDishService.updateByIdWithFlavor(dishDto);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("修改成功!");
    }


    /**
     * 获取菜品分类的信息
     * 使用dish为了后期可能的扩展
     * 时刻注意封装的思想
     * 将菜品信息保存到redis缓存中，减轻数据库高并发时的访问压力
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //应该先去redis缓存中查询
        //查询条件为分类ID和status
        List<DishDto> dishDtoList = null;
        String keys = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(keys);
        //如果redis缓存中有，就直接获取，速度远快于数据库查询
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }
        //如果没有就去数据库查询，正常执行
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //根据id和起售状态查询
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //集合查询
        List<Dish> dishList = iDishService.list(queryWrapper);

        dishDtoList = dishList.stream().map((item) -> {
            //要返回dishdto看iiu需要先new一个
            DishDto dishDto = new DishDto();
            //将每一个dish里的数据copy到dto中
            BeanUtils.copyProperties(item, dishDto);
            //因为dish没有口味信息以及菜系名称，所以需要根据id获得
            //先获取分类的id
            Long categoryId = item.getCategoryId();
            Category category = iCategoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //获取菜品口味信息，根据当前菜品id查询
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            flavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavorList = iDishFlavorService.list(flavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //查询完后应该把相应分类的数据全都存入redis
        redisTemplate.opsForValue().set(keys, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);

    }


    /**
     * 通用菜品状态修改
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {
        log.info("修改状态的菜品状态为:{}", status);
        log.info("需要修改状态的菜品ID为:{}", ids);
        //条件过滤器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null, Dish::getId, ids);
        List<Dish> dishList = iDishService.list(queryWrapper);
        for (Dish dish : dishList) {
            if (dish != null) {
                dish.setStatus(status);
                iDishService.updateById(dish);
            }
        }
        return R.success("状态修改成功!");
    }


    /**
     * 菜品删除
     * @param ids
     * @return
     */
    @DeleteMapping()
    public R<String> removeByIds(@RequestParam("ids") List<Long> ids) {
        log.info("要删除的菜品ID为:{}", ids);

        //需要先查询该菜品是否关联了套餐,是哪些,否则无法删除
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getDishId, ids);
        List<SetmealDish> setmealDishList = iSetmealDishService.list(queryWrapper);

        if (setmealDishList.size() == 0) {
            //如果没有关联套餐,在判断菜品是否在售,否则不能删除
            iDishService.deleteByIds(ids);
            //并且口味表的相应数据也要删除
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.in(DishFlavor::getDishId, ids);
            iDishFlavorService.remove(dishFlavorLambdaQueryWrapper);
            return R.success("删除成功!");
        }

        //如果有关联套餐,那就查看套餐是否在售
        //需要从setmealdish查出setmealID，再去setmeal表查询套餐状态，因为可能有多个setmealId,所以用集合装起来
        ArrayList<Long> setIdList = new ArrayList<>();
        for (SetmealDish setmealDish : setmealDishList) {
            String setmealId = setmealDish.getSetmealId();
            setIdList.add(Long.parseLong(setmealId));
        }

        //再根据套餐id去查询看是否有对应的套餐再出售
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.in(Setmeal::getId, setIdList);
        List<Setmeal> setmealList = iSetmealService.list(setmealLambdaQueryWrapper);

        //遍历套餐查看状态
        for (Setmeal setmeal : setmealList) {
            Integer status = setmeal.getStatus();
            if (status == 1) {
                //在售就不能删除
                return R.error("该菜品管理的套餐正在售卖!不能删除!");
            }
        }

        //没有在售那就可以删除，同时还需要判断一下菜品是否在售
        iDishService.deleteByIds(ids);

        //再去删除口味表数据
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.in(DishFlavor::getDishId, ids);
        iDishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        return R.success("删除成功!");
    }


}
